package com.note.simpleadmin.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.LongSerializationPolicy;
import com.google.gson.reflect.TypeToken;
public class GsonUtil {
	public static String toGson(Object obj) {
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
				.serializeNulls().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
		return gson.toJson(obj);
	}
	public static String toGsonNotNull(Object obj) {
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
		return gson.toJson(obj);
	}
	public static String toGson(Object obj, String regex) {
		Gson gson = new GsonBuilder().setDateFormat(regex).create();
		return gson.toJson(obj);
	}
	public static <T> T fromJson(String str,Class<T>  cla) {
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		T entity = gson.fromJson(str,cla);
		return entity;
	}
	@SuppressWarnings("unchecked")
	public static Map<String, Object> fromJsonToMap(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, Map.class);
	}
	public static List<Long> longsfromJson(String ids) {
		Gson gson = new Gson();
		List<Long> listIds = gson.fromJson(ids, new TypeToken<List<Long>>() {
		}.getType());
		return listIds;
	}
	public static <T> List<T> fromJsonList(String jsonString,Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			Gson gson = new Gson();
			JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
			for (JsonElement jsonElement : arry) {
				list.add(gson.fromJson(jsonElement, cls));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}